package com.ltcode.sys.application.service;

import cn.hutool.core.util.StrUtil;
import com.ltcode.common.base.constant.UserConstants;
import com.ltcode.sys.domain.model.SysRole;
import com.ltcode.sys.domain.model.SysUser;
import com.ltcode.sys.domain.repository.SysMenuRepository;
import com.ltcode.sys.domain.repository.SysRoleRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class SysPermissionAppService {
    private final SysRoleRepository sysRoleRepository;
    private final SysMenuRepository sysMenuRepository;
    /**
     * 获取角色权限
     *
     * @param user 用户信息
     * @return 权限列表
     */
    public Set<String> getRolePermission(SysUser user) {
        Set<String> perms = new HashSet<String>();
        if (user.isAdmin())
        {
            perms.add("admin");
            return perms;
        }
        List<SysRole> sysRoles =
                sysRoleRepository.selectRolePermissionByUserId(user.getUserId());
        return sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());

    }

    public Set<String> getMenuPermission(SysUser user) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            List<SysRole> roles = user.getRoles();
            if (!CollectionUtils.isEmpty(roles))
            {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles)
                {
                    if (StrUtil.equals(role.getStatus(), UserConstants.ROLE_NORMAL) && !role.isAdmin())
                    {
                        Set<String> rolePerms = sysMenuRepository.selectMenuPermsByRoleId(role.getRoleId());
                        role.setPermissions(rolePerms);
                        perms.addAll(rolePerms);
                    }
                }
            }
            else
            {
                perms.addAll(sysMenuRepository.selectMenuPermsByUserId(user.getUserId()));
            }
        }
        return perms;
    }
}
